﻿using System;
using System.Text;
using System.Security.Cryptography;
using WxPayAPI;
using BCCommon;

namespace BCService.Common.Payment.Payment.WeixinPay
{
    /// <summary>
    /// 微信支付退款通知解密
    /// </summary>
    public class WeixinPayRefundNotifyService : Notify
    {
        /// <summary>
        /// AES-256-ECB字符解密
        /// </summary>
        /// <param name="s">要解密字符串</param>
        /// <param name="key">密钥</param>
        /// <returns></returns>
        public static string DecodeAES256ECB(string s, string key)
        {
            string r = null;
            try
            {
                byte[] keyArray = UTF8Encoding.UTF8.GetBytes(key);
                byte[] toEncryptArray = Convert.FromBase64String(s);
                RijndaelManaged rDel = new RijndaelManaged();
                rDel.Key = keyArray;
                rDel.Mode = CipherMode.ECB;
                rDel.Padding = PaddingMode.PKCS7;
                ICryptoTransform cTransform = rDel.CreateDecryptor();
                byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);
                r = UTF8Encoding.UTF8.GetString(resultArray);
            }
            catch(Exception e) {
                Console.WriteLine(e.Message);
            }
            return r;
        }
        /// <summary>
        /// 解密微信支付退款结果通知
        /// </summary>
        /// <param name="s">要解密字符串</param>
        /// <param name="key">解密秘钥</param>
        /// <returns></returns>
        public static string DecodeReqInfo(string s,string key)
        {
            string r = null;
            System.Security.Cryptography.MD5 md5 = System.Security.Cryptography.MD5.Create();
            string decodeKey = BitConverter.ToString(md5.ComputeHash(Encoding.UTF8.GetBytes(key))).Replace("-", null).ToLower();
            r = DecodeAES256ECB(s, decodeKey);
            return r;
        }
        /// <summary>
        /// 微信通知数据
        /// </summary>
        private WxPayData notifyData;

        /// <summary>
        /// 处理微信通知
        /// </summary>
        /// <param name="returnXml">接受的通知Xml</param>
        /// <param name="decodeKey">解密Key</param>
        public string ProcessNotify(string returnXml,string decodeKey)
        {
            WxPayData wxPayData = new WxPayData();
            var dic = wxPayData.FromXmlWithNoneCheckSign(returnXml);
            notifyData = GetNotifyData();
            string req_info = DecodeReqInfo(dic["req_info"].ToString(),decodeKey);
            return req_info;
        }
    }
}